from flask import jsonify, request, g
from flask.views import MethodView

from app.apis.v1 import api_v1
from app.models import User
from app.extensions import db
from app.apis.v1.schemas import user_schema, loan_schema
from app.apis.v1.auth import auth_required, generate_token


def get_data(key):
    if request.get_json():
        return request.get_json().get(key)
    return None


class UserAPI(MethodView):
    decorators = [auth_required]

    def get(self):
        return jsonify(user_schema(g.current_user))


class LoanAPI(MethodView):
    decorators = [auth_required]

    def get(self):
        return jsonify(loan_schema(g.current_user))


class AuthTokenAPI(MethodView):

    def post(self):
        grant_type = request.form.get('grant_type')
        mobile = request.form.get('mobile')

        if grant_type is None or grant_type.lower() != 'password':
            return jsonify(code=400, message='The grant type must be password.')

        user = User.query.filter_by(mobile=mobile).first()
        if user is None:
            return jsonify(code=401, message='Either the username or password was invalid.')

        token, expiration = generate_token(user)

        response = jsonify({
            'token': token,
            'token_type': 'Bearer',
            'mobile': mobile,
            'id': user.id,
            'expires_in': expiration
        })
        response.headers['Cache-Control'] = 'no-store'
        response.headers['Pragma'] = 'no-cache'
        return response


api_v1.add_url_rule('/oauth/token', view_func=AuthTokenAPI.as_view('token'), methods=['POST'])
api_v1.add_url_rule('/user', view_func=UserAPI.as_view('user'), methods=['GET'])
api_v1.add_url_rule('/loan', view_func=LoanAPI.as_view('loan'), methods=['GET'])
